import axios, { AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios'

const tokenExpired = 60 * 60 * 1000

axios.defaults.validateStatus = function(status) {
  return status < 400
}

const instance = axios.create({
  withCredentials: true,
  timeout: 60 * 1000 * 2,
  headers: {
    originalUrl: window.location.href
  }
})

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('TOKEN');
    if (token) { 
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

function refreshToken(response: AxiosResponse) {
  const token = response.headers.authentication
  if (token) {
    setToken(token)
  }
  return response
}

export default function request(
  url: string | AxiosRequestConfig, 
  options?: AxiosRequestConfig
): AxiosPromise<{code: number, msg: string, data: any}> {
  const axiosPromise = typeof url === 'string' ? instance(url, options) : instance(url)
  return axiosPromise
    .then(refreshToken)
}

export function setToken(token: string) {
  localStorage.setItem('TOKEN', token)
  localStorage.setItem('TOKEN_EXPIRE', `${new Date().getTime() + tokenExpired}`)
}

export function removeToken() {
  localStorage.removeItem('TOKEN')
  localStorage.removeItem('TOKEN_EXPIRE')
}
